import ky from 'ky'
import { message } from 'ant-design-vue'

const baseRquest = ky.create({
  prefixUrl: 'http://localhost:8123',
  retry: 0,
  timeout: 60000,
  hooks: {
    beforeRequest: [
      async (request) => {
        //     let token = getToken();
        //     if (token) {
        //       request.headers.set('UserToken', `${token}`);
        //     } else {
        //       if (!cacheLoginRequest) {
        //         cacheLoginRequest = getTokenService();
        //       }
        //       try {
        //         const loginRes = await cacheLoginRequest;
        //         if (loginRes?.code === 200 && loginRes.data) {
        //           token = loginRes.data;
        //           setToken(token);
        //           request.headers.set('UserToken', `${token}`);
        //         } else {
        //           goToLogin();
        //         }
        //       } catch (_error) {
        //         console.error('获取token失败', _error);
        //         goToLogin();
        //       }
        //     }
      },
    ],
    afterResponse: [
      (_request, _options, response) => {
        if (response.status === 40100) {
          if (
            !response.url.includes('user/get/login') &&
            !window.location.pathname.includes('/user/login')
          ) {
            message.warning('请先登录')
            window.location.href = `/user/login?redirect=${window.location.href}`
          }
        }
      },
    ],
  },
})

export const request = baseRquest.extend({})
